package com.cn.zpark.controller;

import com.cn.zpark.pojo.User;
import com.cn.zpark.service.IUserService;
import com.cn.zpark.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @PackageName: com.cn.zpark.controller
 * @ClassName: LoginUserServletController
 * @Description:
 * @author: RZS
 * @date: 2022/5/24  22:49
 */
@WebServlet("/user_login.do")
public class LoginUserServletController extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 调用service执行登录业务
        User user = userService.login(username, password);

        // 判断查询结果是否未null
        if (user == null) {
            // user为null，登录失败
            // 绑定登陆错误信息
            request.setAttribute("message", "用户名或密码错误");
            // 转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }else {
            // 查询结果不为null，则绑定user数据到session对象中，转发到系统首页
            // 获取session对象
            HttpSession session = request.getSession();
            // 绑定数据到session对象中
            session.setAttribute("user", user);
            // 转发到首页
            request.getRequestDispatcher("/view/index.jsp").forward(request, response);
        }

    }
}
